<?php

$data = array();
$data['errors'] = array();

if (isset($_GET['author_id'])) {
    $data['author']['author_id'] = (int) ($_GET['author_id']);
    $authorQuery = mysqli_query($connection, 'SELECT * FROM authors WHERE author_id = ' . $data['author']['author_id']);

    if (mysqli_num_rows($authorQuery) > 0) {
        $row = mysqli_fetch_assoc($authorQuery);
        $data['author']['author_name'] = $row['author_name'];

        $sql = 'SELECT b.book_id, b.book_title, ba1.author_id, a1.author_name
                FROM authors as a
                INNER JOIN books_authors as ba ON a.author_id=ba.author_id
                INNER JOIN books_authors as ba1 on ba1.book_id = ba.book_id
                INNER JOIN books as b ON b.book_id=ba.book_id
                INNER JOIN authors as a1 ON ba1.author_id = a1.author_id
                WHERE a.author_id = ' . $data['author']['author_id'];
        $query = mysqli_query($connection, $sql);
        $data['books'] = array();
        $authors = array();
        while ($row = mysqli_fetch_assoc($query)) {
            $data['books'][$row['book_id']]['book_title'] = $row['book_title'];
            $data['books'][$row['book_id']]['book_id'] = $row['book_id'];
            $authors['id'] = $row['author_id'];
            $authors['name'] = $row['author_name'];
            $data['books'][$row['book_id']]['authors'][] = $authors;
        }
    } else {
        $data['errors'][] = 'Този автор не e намерен';
    }
} else {
    header('Location: index.php');
    exit();
}

$data['title'] = 'Автор';
render($data, 'templates/author_public.php');